﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Diagnostics;
using System.Windows.Input;
using System.Dynamic;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using ViewMaker.Core.Controls;
using System.Windows.Media;
using System.Windows.Markup;
using System.Windows.Interactivity;
using ViewMaker.Core.Utils;

namespace ViewMaker.Core.Silverlight
{
    public class SlChildWindowView : IView
    {
        public ChildWindow window;
        private ContentControl conetnt;

        public SlChildWindowView(ContentControl content, ViewLayoutItem root, object viewModel)
        {
            this.window = new ChildWindow();
            this.window.DataContext = viewModel;
            this.conetnt = content;
            this.window.Content = this.conetnt;
            this.window.Title = root.Caption;
            SetWindowsInfo(root);
            var behavior = new ViewCommandBehavior { Helper = ServiceLocator.GetService<IViewCommandHelper>() };
            Interaction.GetBehaviors(window).Add(behavior);
        }

        private void SetWindowsInfo(ViewLayoutItem root)
        {
            if (root.Caption != null) this.window.Title = root.Caption;
            var winSettigs = root.Control.WindowSettings;
            if (winSettigs.Height.HasValue) window.Height = winSettigs.Height.Value;
            if (winSettigs.Width.HasValue) window.Width = winSettigs.Width.Value;
            if (winSettigs.FontSize.HasValue) window.FontSize = winSettigs.FontSize.Value;
            if (!string.IsNullOrEmpty(winSettigs.Foreground)) window.Foreground = SilverlightUtil.GetColor(winSettigs.Foreground);
            if (!string.IsNullOrEmpty(winSettigs.Background)) window.Background = SilverlightUtil.GetColor(winSettigs.Background);
            if (!string.IsNullOrEmpty(winSettigs.ClosingCommand))
            {
                var behavior = new ChildWindowClosingBehavior();
                BindingOperations.SetBinding(behavior, ChildWindowClosingBehavior.CommandProperty, new Binding(winSettigs.ClosingCommand));
                Interaction.GetBehaviors(window).Add(behavior);
            }
        }

        #region IView メンバー

        public void Show()
        {
            window.Show();
        }

        public void ShowDialog()
        {
            window.Show();
        }

        public void Close()
        {
            window.Close();
        }

        #endregion

        #region IViewContent メンバー

        public object Content
        {
            get { return conetnt; }
        }

        #endregion
    }
    
 
}
